package com.tron.utils.tron;

import org.springframework.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CrosFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        //*号表示对所有请求都允许跨域访问
        resp.setHeader("Access-Control-Allow-Origin", "*");
        // resp.addHeader("Access-Control-Allow-Origin", "*");
        resp.addHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
        resp.setHeader("Access-Control-Allow-Headers", "*");
        resp.setHeader("Access-Control-Max-Age", "86400");
        resp.setHeader("Access-Control-Allow-Headers", "Authorization");

        if (req.getMethod().equals("OPTIONS")) {

            resp.setStatus(HttpStatus.OK.value());

            // hresp.setContentLength(0);

            resp.getWriter().write("OPTIONS returns OK");

            return;

        }
        // Filter 只是链式处理，请求依然转发到目的地址。

        filterChain.doFilter(req, resp);

    }

    @Override
    public void destroy() {

    }
}

